package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.GridViewAdapter;
import com.shaoshaohuo.app.entity.AddNewAddressEntity;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.BitmapUtils;
import com.shaoshaohuo.app.utils.Okhttputils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Response;

public class BusinessApllyMessageActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener {
    /**
     * tobar
     */
    private ImageView order_tobar_back;
    private TextView order_tobar_enter;
    private ImageView order_tobar_right;
    private LinearLayout order_layout_topbar_left;
    private Button farm_finish;
    private EditText farm_scale;
    private EditText farm_details_address;
    private TextView farm_address;
    private RelativeLayout farm_select_farm_address;
    private EditText farm_id;
    private EditText farm_phone;
    private EditText farm_name;
    private TextView fram_sex_boy;
    private TextView farm_sex_girl;
    private String s_farm_id;
    private String s_farm_scale;
    private String s_farm_name;
    private String s_farm_phone;
    private String s_farm_details_address;
    private String s_farm_address;


    private TextView apply_farm_add_picture;
    private GridView apply_farm_gridView;
    private List<String> picture_data;//显示图片
    private List<File> file;
    private GridViewAdapter adapter;
    private String province;
    private String county;
    private String c;
    private String latitude;
    private String longitude;

    private int sex = 1;
    private HorizontalScrollView release_shop_horscrolistView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_aplly_message);
        initView();
        initListener();
    }

    private void initListener() {
        farm_name.setOnTouchListener(this);
        farm_phone.setOnTouchListener(this);
        farm_id.setOnTouchListener(this);
        farm_select_farm_address.setOnClickListener(this);
        farm_address.setOnClickListener(this);
        farm_details_address.setOnTouchListener(this);
//        farm_scale.setOnTouchListener(this);
        farm_finish.setOnClickListener(this);
        fram_sex_boy.setOnClickListener(this);
        farm_sex_girl.setOnClickListener(this);
        apply_farm_add_picture.setOnClickListener(this);
        order_layout_topbar_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void initView() {
        /**
         * tobar
         * */
        order_tobar_back = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        order_tobar_back.setVisibility(View.VISIBLE);
        order_tobar_back.setImageResource(R.mipmap.return_key);
        order_tobar_enter = (TextView) findViewById(R.id.toolbar_topname);
        order_tobar_enter.setText("完善个人信息");
        order_tobar_right = (ImageView) findViewById(R.id.imageview_message);
        order_tobar_right.setVisibility(View.GONE);
        order_layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        order_layout_topbar_left.setVisibility(View.VISIBLE);

        farm_finish = (Button) findViewById(R.id.farm_finish);
        farm_address = (TextView) findViewById(R.id.farm_address);
        farm_select_farm_address = (RelativeLayout) findViewById(R.id.farm_select_farm_address);
        farm_scale = (EditText) findViewById(R.id.farm_scale);
        farm_details_address = (EditText) findViewById(R.id.farm_details_address);
        farm_id = (EditText) findViewById(R.id.farm_id);
        farm_phone = (EditText) findViewById(R.id.farm_phone);
        farm_name = (EditText) findViewById(R.id.farm_name);
        fram_sex_boy = (TextView) findViewById(R.id.fram_sex_boy);
        farm_sex_girl = (TextView) findViewById(R.id.farm_sex_girl);
        apply_farm_gridView = (GridView) findViewById(R.id.apply_farm_gridView);
        apply_farm_gridView.setNumColumns(4);
        apply_farm_add_picture = (TextView) findViewById(R.id.apply_farm_add_picture);
        picture_data = new ArrayList<>();
        file = new ArrayList<>();

        release_shop_horscrolistView = (HorizontalScrollView) findViewById(R.id.release_shop_horscrolistView);
    }

    private void CancelHint(EditText editText) {
        editText.setHint("");
        editText.setCursorVisible(true);
        editText.setSelection(editText.getText().toString().trim().length());
    }

    private ArrayList<String> pathlist = new ArrayList<>();


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.farm_scale:
                CancelHint(farm_scale);
                break;
            case R.id.farm_details_address:
                CancelHint(farm_details_address);
                break;
            case R.id.farm_id:
                CancelHint(farm_id);
                break;
            case R.id.farm_phone:
                CancelHint(farm_phone);
                break;
            case R.id.farm_name:
                CancelHint(farm_name);
                break;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == 2) {
            AddNewAddressEntity address = (AddNewAddressEntity) data.getSerializableExtra("address");
            if (address != null) {
                String addressname = address.getAddressname();
                farm_details_address.setText(addressname);
                farm_details_address.setSelection(farm_details_address.getText().toString().trim().length());
                latitude = address.getLatitude();
                longitude = address.getLongitude();
                c = address.getIntent_city();
                address.getProvince();
                province = address.getProvince();
                county = address.getDistrict();
                Log.e("地址", c + province + county);
                Toast.makeText(getApplicationContext(), c + province + county, Toast.LENGTH_SHORT).show();
            }
        }

        if (requestCode == 6) {
            if (data != null) {
                ArrayList<String> select_more_result = data.getStringArrayListExtra("select_result");
                if (select_more_result != null && select_more_result.size() > 0) {
                    for (int i = 0; i < select_more_result.size(); i++) {
                        String more_picture = select_more_result.get(0);
                        File zipbit = BitmapUtils.zipbit(more_picture, getApplicationContext());
//                        File picture_file = new File(more_picture);
                        file.add(zipbit);
                        picture_data.add(zipbit.getAbsolutePath());
                    }
                    if (picture_data != null && picture_data.size() > 0) {
                        release_shop_horscrolistView.setVisibility(View.VISIBLE);
                        apply_farm_gridView.setVisibility(View.VISIBLE);
                        if (picture_data.size() >= 6) {
                            apply_farm_add_picture.setVisibility(View.GONE);
                        }
                        adapter = new GridViewAdapter(getApplicationContext(), picture_data);
                        horizontal_layout();
                        apply_farm_gridView.setAdapter(adapter);
                        adapter.setDelete(new GridViewAdapter.Delete() {
                            @Override
                            public void delete() {
                                if (adapter.getCount() < 6) {
                                    apply_farm_add_picture.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }
                }
            }
        }


    }

    public void horizontal_layout() {
        int size = picture_data.size();
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int allWidth = (int) (110 * size * density);
        int itemWidth = (int) (100 * density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                allWidth, LinearLayout.LayoutParams.FILL_PARENT);
        apply_farm_gridView.setLayoutParams(params);// 设置GirdView布局参数
        apply_farm_gridView.setColumnWidth(itemWidth);// 列表项宽
        apply_farm_gridView.setHorizontalSpacing(5);// 列表项水平间距
        apply_farm_gridView.setStretchMode(GridView.NO_STRETCH);
        apply_farm_gridView.setNumColumns(size);//总长度
    }

    public static void tackPic(ArrayList<String> mSelectPath, Intent intent2, int selectedMode, int maxNum) {
//        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
//        int maxNum = 10;
//        Intent intent2 = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent2.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }

    }

    private void getTextmMessage() {
        if (fram_sex_boy.isSelected()) {
            sex = 1;
        } else if (farm_sex_girl.isSelected()) {
            sex = 2;
        }
        s_farm_address = farm_address.getText().toString().trim();
        s_farm_name = farm_name.getText().toString().trim();
        s_farm_phone = farm_phone.getText().toString().trim();
        s_farm_id = farm_id.getText().toString().trim();
        s_farm_details_address = farm_details_address.getText().toString().trim();
        s_farm_scale = farm_scale.getText().toString().trim();
        if (s_farm_name == null || s_farm_name.length() <= 0) {
            Toast.makeText(getApplicationContext(), "请输入姓名", Toast.LENGTH_SHORT).show();
        } else if (s_farm_phone == null || s_farm_phone.length() <= 0) {
            Toast.makeText(getApplicationContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
        } else if (s_farm_id == null || s_farm_id.length() <= 0) {
            Toast.makeText(getApplicationContext(), "请输入身份证号", Toast.LENGTH_SHORT).show();
        } else if (s_farm_details_address == null || s_farm_details_address.length() <= 0) {
            Toast.makeText(getApplicationContext(), "请输入详细地址", Toast.LENGTH_SHORT).show();
        } else if (s_farm_scale == null || s_farm_scale.length() <= 0) {
            Toast.makeText(getApplicationContext(), "请输入农场规模", Toast.LENGTH_SHORT).show();
        } else {
//            Toast.makeText(getApplicationContext(), "可以跳了", Toast.LENGTH_SHORT).show();
            commitApply();
        }
    }

    private void commitApply() {
        Log.e("青==", file.size() + "==" + s_farm_name + "==" + sex + "==" + s_farm_phone + "==" + s_farm_id + "==" + s_farm_details_address + "==" + s_farm_scale);
        ShopHttpConfig.applyFarm(getApplicationContext(), file, s_farm_name, sex + "", s_farm_phone, s_farm_id, s_farm_details_address, s_farm_scale, "1", new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(final Call call, final int code) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "失败" + code, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void suseff(Call call, Response response, Object o) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "提交成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(getApplicationContext(), WaitCheckActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
            }
        }, BaseEntity.class);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.farm_finish:
                getTextmMessage();
                break;
            case R.id.fram_sex_boy:
                fram_sex_boy.setBackground(getResources().getDrawable(R.drawable.xuanzhong));
                farm_sex_girl.setBackground(getResources().getDrawable(R.drawable.sexweixuanzhong));
                fram_sex_boy.setSelected(true);
                farm_sex_girl.setSelected(false);
                farm_sex_girl.setBackground(null);
                break;
            case R.id.farm_sex_girl:
                farm_sex_girl.setBackground(getResources().getDrawable(R.drawable.xuanzhong));
                fram_sex_boy.setBackground(getResources().getDrawable(R.drawable.sexweixuanzhong));
                fram_sex_boy.setSelected(false);
                farm_sex_girl.setSelected(true);
                fram_sex_boy.setBackground(null);
                break;
            case R.id.apply_farm_add_picture:
                Intent intent_caizhai_picture = new Intent();
                tackPic(pathlist, intent_caizhai_picture, 1, 6);
                intent_caizhai_picture.setClass(getApplicationContext(), MultiImageSelectorActivity.class);
                startActivityForResult(intent_caizhai_picture, 6);
                break;
            case R.id.farm_select_farm_address:
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), AdderssPOIActivity.class);
                startActivityForResult(intent, 10);
                break;
        }
    }

}
